package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.GetDeparmentUserService;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.DepartmentRepository;
import com.ugoodtech.mdcc.core.repository.StationReportRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GetDeparmentUserServiceImpl implements GetDeparmentUserService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;


    @Autowired
    private StationReportRepository stationReportRepository;


    /**
     * 获取报告中指定的部门负责人
     *
     * @param reportId
     * @param userIds
     * @return
     */
    @Override
    public JsonResponse getReportPointUser(Long reportId, String userIds) {
        StationReport stationServiceReport = stationReportRepository.findOne(reportId);
        if (stationServiceReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该报告");
        }
        if (StringUtils.isEmpty(userIds)) {
            return JsonResponse.errorResponseWithError("抱歉", "该报告没有指定部门");
        }
        String[] ids = userIds.split(",");
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder;
        List<Department> departmentList = new ArrayList<>();
        for (String id : ids) {
            builder = new BooleanBuilder();
            builder.and(qDepartment.deleted.eq(false));
            builder.and(qDepartment.id.eq(Long.valueOf(id)));
            Department department = departmentRepository.findOne(builder);
            if (department == null) {
                continue;
            }
            departmentList.add(department);
        }
        List<DeparmentVO> deparmentVOS = toDeparentVO(departmentList);
        return JsonResponse.successResponseWithData(deparmentVOS);
    }


    /**
     * 获得超级父类部门
     *
     * @return
     */
    @Override
    public JsonResponse getSuperDeparment() {
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qDepartment.deleted.eq(false));
        builder.and(qDepartment.parent.isNull());
        List<Department> departmentList = (List<Department>) departmentRepository.findAll(builder);
        List<DeparmentVO> deparmentVOS = toDeparentVO(departmentList);
        return JsonResponse.successResponseWithData(deparmentVOS);
    }

    /**
     * 获取子部门
     *
     * @param parentId
     * @return
     */
    @Override
    public JsonResponse getChildrenDeparment(Long parentId, String name) {
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qDepartment.deleted.eq(false));
        builder.and(qDepartment.parent.isNotNull());
        builder.and(qDepartment.parent.id.eq(parentId));
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qDepartment.name.like("%" + name + "%"));
        }
        List<Department> departmentList = (List<Department>) departmentRepository.findAll(builder);
        List<DeparmentVO> deparmentVOS = toDeparentVO(departmentList);
        return JsonResponse.successResponseWithData(deparmentVOS);
    }

    private List<DeparmentVO> toDeparentVO(List<Department> departmentList) {
        List<DeparmentVO> deparmentVOList = new ArrayList<>();
        for (Department department : departmentList) {
            DeparmentVO dvo = new DeparmentVO();
            dvo.setDeparmentId(department.getId());
            dvo.setDeparmentName(department.getName());
            dvo.setTotalName(department.getTotalName());
            if (department.getLeader() != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(department.getLeader().getId());
                if (userProfile == null) {
                    dvo.setLeaderName("");
                } else {
                    dvo.setLeaderName(userProfile.getRealName());
                }
            } else {
                dvo.setLeaderName("");
            }


            deparmentVOList.add(dvo);
        }
        return deparmentVOList;
    }

    @Override
    public List<Department> getFirstDepartments() {
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(builder.and(qDepartment.deleted.eq(false)));
        builder.and(builder.and(qDepartment.enabled.eq(true)));
        builder.and(builder.and(qDepartment.parent.isNull()));
        Page<Department> page = departmentRepository.findAll(builder, new PageRequest(0, 1000));
        if (null != page.getContent()) {
            return page.getContent();
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<Department> getChildDepartments(Long parentId) {
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(builder.and(qDepartment.deleted.eq(false)));
        builder.and(builder.and(qDepartment.parent.id.eq(parentId)));
        Page<Department> page = departmentRepository.findAll(builder, new PageRequest(0, 10000));
        if (null != page.getContent()) {
            return page.getContent();
        } else {
            return new ArrayList<>();
        }
    }

    private static final Logger logger = LoggerFactory.getLogger(GetDeparmentUserServiceImpl.class);


}
